<template>
    <!--  map_container 必须是固定的-->
    <div id="allmap"></div>
</template>
<script>
//import "_c/import-es5js/importJs.js"
import {BMapGLLoader, BMapLoader, BMapGLJs, BMapLoadMapv} from "_c/import-es5js/BMapLoader"
export default {
  props: {
    devices: {
      type: Array,
      default: () => []
    },
    mapInfo: {
      type: Object,
      default:()=>{
        return{
          centerLongitude:114.236262,
          centerLatitude:22.677236,
          minZoom:2,
          maxZoom:20,
          defaultZomm:10,
          mode: 'ONLINE'
        }
      }

    },
  },
  watch:{
    devices(oldVal,newVal){
      console.log("oldVal:%o,newVal:%o",oldVal,newVal)
      this.aggDeviceData();
    }
  },
  data() {
    return {
      map:null,
      data:[],
      citys:[],

      randomCount:1000,
      view:null,
      clusterLayer:null,
      mapv:null

    }
  },
  created() {
    this.createMap()
  },
  destroyed() {
    if (!!this.map){
      this.map.destroy();
    }

  },
  methods: {
    createMap1(){
      BMapLoader('IfkNE0XDdoaTwdGGkOWrALDkFZOTI9b8').then(BMap => {
        //BMapGLJs("https://mapv.baidu.com/build/mapv.js");
        const map = new BMap.Map('allmap', { enableMapClick: false });
        map.disableKeyboard() // 禁用键盘操作地图
        map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
        const point = new BMap.Point(106.78887812364171, 29.666046706760273)
        map.centerAndZoom(point, 9);
        //map.setMapStyle({style:'midnight'});
        this.map=map;

        BMapLoadMapv("123").then(mapv => {
          console.log("out BMapLoadMapv(src)");
          this.citys=[
            '北京',
            '天津',
            '上海',
            '重庆',
            '石家庄',
            '太原',
            '呼和浩特',
            '哈尔滨',
            '长春',
            '沈阳',
            '济南',
            '南京',
            '合肥',
            '杭州',
            '南昌',
            '福州',
            '郑州',
            '武汉',
            '长沙',
            '广州',
            '南宁',
            '西安',
            '银川',
            '兰州',
            '西宁',
            '乌鲁木齐',
            '成都',
            '贵阳',
            '昆明',
            '拉萨',
            '海口'
          ];
          console.log("mapv");
          console.log(window.mapv);

        })


        // 构造数据
 /*       while (this.randomCount--) {
          let cityCenter = mapv.utilCityCenter.getCenterByCityName(
            this.citys[parseInt(Math.random() * this.citys.length, 10)]
          );
          this.data.push({
            geometry: {
              type: 'Point',
              coordinates: [cityCenter.lng - 2 + Math.random() * 4, cityCenter.lat - 2 + Math.random() * 4]
            },
            properties: {
              icon: [
                'images/marker.png',
                'images/icons/icon-accident.png',
                'images/icons/icon-location.png',
                'images/icons/icon-airplane.png'
              ][this.randomCount % 4],
              width: this.randomCount % 2 === 0 ? 100 / 4 : 30,
              height: this.randomCount % 2 === 0 ? 153 / 4 : 30
            }
          });
        }*/

        console.log(this.data);
      })
    },
    createMap() {
      this.$nextTick(() => {
        BMapLoader('IfkNE0XDdoaTwdGGkOWrALDkFZOTI9b8').then(BMap => {
          const map = new BMap.Map('allmap', { enableMapClick: false });
          map.disableKeyboard() // 禁用键盘操作地图
          map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
          //const point = new BMap.Point(106.78887812364171, 29.666046706760273)

          const point = new BMap.Point(this.mapInfo.centerLongitude,this.mapInfo.centerLatitude);
          map.centerAndZoom(point, this.mapInfo.defaultZomm);
          //map.setMapStyle({style:'midnight'});
          this.map=map;
        });
        BMapLoadMapv("123").then(mapv => {
          console.log("after BMapLoadMapv");
        })
      })

    },
    aggDeviceData(){
      // 参考 http://mapv.baidu.com/examples/#baidu-map-point-cluster.html
      console.log("devices: %o",this.devices);
      this.data=[];

      for(let i in this.devices){
        this.data.push({
          geometry: {
            type: 'Point',
            coordinates: [this.devices[i].lng - 5 + Math.random() * 10, this.devices[i].lat - 5 + Math.random() * 10]
          },
          iconOptions: {
            url: [
              'images/flag.png',
              'images/marker.png',
              'images/star.png'][this.devices.length % 3],
            width: 50/3,
            height: this.devices.length % 3 === 2 ? 50 / 3 : 77/3
          }
        });
        let dataSet = new mapv.DataSet(this.data);

        let options = {
          // shadowColor: 'rgba(255, 250, 50, 1)',
          // shadowBlur: 10,
          // 非聚合点的颜色和大小，未设置icon或icon获取失败时使用
          fillStyle: 'rgba(255, 50, 0, 1.0)',
          size: 50 / 3 / 2, // 非聚合点的半径
          // 非聚合时点的icon设置，会被具体点的设置覆盖，可设置为空
          // iconOptions: {
          //     url: 'images/marker.png',
          //     width: 50 / 3,
          //     height: 77 / 3,
          //     offset: {
          //         x: 0,
          //         y: 0
          //     }
          // },
          minSize: 8, // 聚合点最小半径
          maxSize: 31, // 聚合点最大半径
          globalAlpha: 0.8, // 透明度
          clusterRadius: 150, // 聚合像素半径
          maxClusterZoom: 18, // 最大聚合的级别
          maxZoom: 15, // 最大显示级别
          minZoom: 5, // 最大显示级别
          showText: true, //
          minPoints: 5, // 最少聚合点数，点数多于此值才会被聚合
          extent: 400, // 聚合的细腻程度，越高聚合后点越密集
          label: { // 聚合文本样式
            show: true, // 是否显示
            fillStyle: 'white',
            // shadowColor: 'yellow',
            // font: '20px Arial',
            // shadowBlur: 10,
          },
          //gradient: { 0: "blue", 0.5: 'yellow', 1.0: "rgb(255,0,0)"}, // 聚合图标渐变色
          gradient: { 0: "blue", 0.5: 'green', 1.0: "red"},
          draw: 'cluster',
          methods: {
            click(point) {
              if (point) {
                if (point.iconOptions) {
                  console.log(point.iconOptions.url);
                }
                // 通过children可以拿到被聚合的所有点
                console.log(point.children);
              }
            }
          }
        }
        let mapvLayer = new mapv.baiduMapLayer(this.map, dataSet, options);

      }
    },
    aggData() {
      // 参考 http://mapv.baidu.com/examples/#baidu-map-point-cluster.html
      //升成聚合数据
      console.log("mapv:%o",mapv);
      this.citys = ['北京', '天津', '上海', '重庆', '石家庄', '太原', '呼和浩特', '哈尔滨', '长春', '沈阳',
        '济南', '南京', '合肥', '杭州', '南昌', '福州', '郑州', '武汉', '长沙', '广州', '南宁', '西安', '银川',
        '兰州', '西宁', '乌鲁木齐', '成都', '贵阳', '昆明', '拉萨', '海口'];
      // 构造数据
      while (this.randomCount--) {
        let cityCenter = mapv.utilCityCenter.getCenterByCityName(
          this.citys[parseInt(Math.random() * this.citys.length, 10)]
        );
        this.data.push({
          geometry: {
            type: 'Point',
            coordinates: [cityCenter.lng - 5 + Math.random() * 10, cityCenter.lat - 5 + Math.random() * 10]
          },
          iconOptions: {
            url: [
              'images/flag.png',
              'images/marker.png',
              'images/star.png'][this.randomCount % 3],
            width: 50/3,
            height: this.randomCount % 3 === 2 ? 50 / 3 : 77/3
          }
        });
      }

      let dataSet = new mapv.DataSet(this.data);

      let options = {
        // shadowColor: 'rgba(255, 250, 50, 1)',
        // shadowBlur: 10,
        // 非聚合点的颜色和大小，未设置icon或icon获取失败时使用
        fillStyle: 'rgba(255, 50, 0, 1.0)',
        size: 50 / 3 / 2, // 非聚合点的半径
        // 非聚合时点的icon设置，会被具体点的设置覆盖，可设置为空
        // iconOptions: {
        //     url: 'images/marker.png',
        //     width: 50 / 3,
        //     height: 77 / 3,
        //     offset: {
        //         x: 0,
        //         y: 0
        //     }
        // },
        minSize: 8, // 聚合点最小半径
        maxSize: 31, // 聚合点最大半径
        globalAlpha: 0.8, // 透明度
        clusterRadius: 150, // 聚合像素半径
        maxClusterZoom: 18, // 最大聚合的级别
        maxZoom: 15, // 最大显示级别
        minZoom: 5, // 最大显示级别
        showText: true, //
        minPoints: 5, // 最少聚合点数，点数多于此值才会被聚合
        extent: 400, // 聚合的细腻程度，越高聚合后点越密集
        label: { // 聚合文本样式
          show: true, // 是否显示
          fillStyle: 'white',
          // shadowColor: 'yellow',
          // font: '20px Arial',
          // shadowBlur: 10,
        },
        //gradient: { 0: "blue", 0.5: 'yellow', 1.0: "rgb(255,0,0)"}, // 聚合图标渐变色
        gradient: { 0: "blue", 0.5: 'green', 1.0: "red"},
        draw: 'cluster',
        methods: {
          click(point) {
            if (point) {
              if (point.iconOptions) {
                console.log(point.iconOptions.url);
              }
              // 通过children可以拿到被聚合的所有点
              console.log(point.children);
            }
          }
        }
      }
      let mapvLayer = new mapv.baiduMapLayer(this.map, dataSet, options);
    },
    aggData1(){
      //升成聚合数据
      this.citys=[
        '北京',
        '天津',
        '上海',
        '重庆',
        '石家庄',
        '太原',
        '呼和浩特',
        '哈尔滨',
        '长春',
        '沈阳',
        '济南',
        '南京',
        '合肥',
        '杭州',
        '南昌',
        '福州',
        '郑州',
        '武汉',
        '长沙',
        '广州',
        '南宁',
        '西安',
        '银川',
        '兰州',
        '西宁',
        '乌鲁木齐',
        '成都',
        '贵阳',
        '昆明',
        '拉萨',
        '海口'
      ];

      // 构造数据
      while (this.randomCount--) {
        let cityCenter = mapv.utilCityCenter.getCenterByCityName(
          this.citys[parseInt(Math.random() * this.citys.length, 10)]
        );
        this.data.push({
          geometry: {
            type: 'Point',
            coordinates: [cityCenter.lng - 2 + Math.random() * 4, cityCenter.lat - 2 + Math.random() * 4]
          },
          properties: {
            icon: [
              'images/marker.png',
              'images/icons/icon-accident.png',
              'images/icons/icon-location.png',
              'images/icons/icon-airplane.png'
            ][this.randomCount % 4],
            width: this.randomCount % 2 === 0 ? 100 / 4 : 30,
            height: this.randomCount % 2 === 0 ? 153 / 4 : 30
          }
        });
      }

      //
      this.view = new window.mapvgl.View({map: this.map});

      //
      this.clusterLayer = new window.mapvgl.ClusterLayer({
        minSize: 30, // 聚合点显示的最小直径
        maxSize: 50, // 聚合点显示的最大直径
        clusterRadius: 150, // 聚合范围半径
        gradient: {0: 'blue', 0.5: 'green', 1.0: 'red'}, // 聚合点颜色梯度
        maxZoom: 15, // 聚合的最大级别，当地图放大级别高于此值将不再聚合
        minZoom: 5, // 聚合的最小级别，当地图放大级别低于此值将不再聚合
        // 是否显示文字
        showText: true,
        // 开始聚合的最少点数，点数多于此值才会被聚合
        minPoints: 5,
        // 设置文字样式
        textOptions: {
          fontSize: 12,
          color: 'white',
          // 格式化数字显示
          format: function (count) {
            return count >= 10000 ? Math.round(count / 1000) + 'k'
              : count >= 1000 ? Math.round(count / 100) / 10 + 'k' : count;
          }
        },
        // 设置非聚合的点的icon
        // iconOptions: {
        //     width: 100 / 4,
        //     height: 153 / 4,
        //     icon: 'images/marker.png',
        // },
        enablePicked: true,
        onClick(e) {
          if (e.dataItem) {
            // 可通过dataItem下面的children属性拿到被聚合的所有点
            console.log(e.dataItem);
          }
        }
      });

      this.view.addLayer(this.clusterLayer);
      this.clusterLayer.setData(this.data);


    }
  },
  mounted123() {
    /* global BMapGL */
    /* global mapv */
    /* global mapvgl */
    /* global initMap */
    /* global whiteStyle */
    //console.log("mapv: o%",mapv);

 /*   this.map = initMap({
      style: whiteStyle,
      tilt: 10,
      center: [109.792816,27.702774],
      zoom: 5,
      skyColors: [
        // 地面颜色
        'rgba(226, 237, 248, 0)',
        // 天空颜色
        'rgba(186, 211, 252, 1)'
      ]
    });*/

/*
    // 构造数据
    while (this.randomCount--) {
      let cityCenter = mapv.utilCityCenter.getCenterByCityName(
        this.citys[parseInt(Math.random() * this.citys.length, 10)]
      );
      this.data.push({
        geometry: {
          type: 'Point',
          coordinates: [cityCenter.lng - 2 + Math.random() * 4, cityCenter.lat - 2 + Math.random() * 4]
        },
        properties: {
          icon: [
            'images/marker.png',
            'images/icons/icon-accident.png',
            'images/icons/icon-location.png',
            'images/icons/icon-airplane.png'
          ][this.randomCount % 4],
          width: this.randomCount % 2 === 0 ? 100 / 4 : 30,
          height: this.randomCount % 2 === 0 ? 153 / 4 : 30
        }
      });
    }

    //
    this.view = new mapvgl.View({map: this.map});

    //
    this.clusterLayer = new mapvgl.ClusterLayer({
      minSize: 30, // 聚合点显示的最小直径
      maxSize: 50, // 聚合点显示的最大直径
      clusterRadius: 150, // 聚合范围半径
      gradient: {0: 'blue', 0.5: 'green', 1.0: 'red'}, // 聚合点颜色梯度
      maxZoom: 15, // 聚合的最大级别，当地图放大级别高于此值将不再聚合
      minZoom: 5, // 聚合的最小级别，当地图放大级别低于此值将不再聚合
      // 是否显示文字
      showText: true,
      // 开始聚合的最少点数，点数多于此值才会被聚合
      minPoints: 5,
      // 设置文字样式
      textOptions: {
        fontSize: 12,
        color: 'white',
        // 格式化数字显示
        format: function (count) {
          return count >= 10000 ? Math.round(count / 1000) + 'k'
            : count >= 1000 ? Math.round(count / 100) / 10 + 'k' : count;
        }
      },
      // 设置非聚合的点的icon
      // iconOptions: {
      //     width: 100 / 4,
      //     height: 153 / 4,
      //     icon: 'images/marker.png',
      // },
      enablePicked: true,
      onClick(e) {
        if (e.dataItem) {
          // 可通过dataItem下面的children属性拿到被聚合的所有点
          console.log(e.dataItem);
        }
      }
    });

    this.view.addLayer(this.clusterLayer);
    this.clusterLayer.setData(this.data);

    */
  },
  mounted111() {
    //报这个错误：Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
    console.log("初始化百度地图脚本...");
    const AK = "IfkNE0XDdoaTwdGGkOWrALDkFZOTI9b8";
    const BMap_URL = "https://api.map.baidu.com/api?v=2.0&ak="+ AK +"&s=1&callback=onBMapCallback";
    return new Promise((resolve, reject) => {

      // 如果已加载直接返回
      if(typeof BMap !== "undefined") {
        resolve(BMap);
        return true;
      }
      // 百度地图异步加载回调处理
      window.onBMapCallback = function () {
        console.log("百度地图脚本初始化成功...");
        resolve(BMap);
      };
      // 插入script脚本
      let scriptNode = document.createElement("script");
      scriptNode.setAttribute("type", "text/javascript");
      scriptNode.setAttribute("src", BMap_URL);
      document.body.appendChild(scriptNode);

      console.log(window.BMap);
    });

    /** 加入百度地图 */
/*    let src=["https://api.map.baidu.com/api?v=1.0&type=webgl&ak=IfkNE0XDdoaTwdGGkOWrALDkFZOTI9b8",
      //"static/common.js",
      "https://mapv.baidu.com/gl/examples/static/common.js",
      "https://mapv.baidu.com/build/mapv.min.js",
      "https://unpkg.com/mapvgl@1.0.0-beta.168/dist/mapvgl.min.js"
    ]


    for(let i = 0; i < src.length; i++){
      let script = document.createElement('script');
      script.type = "text/javascript";
      console.log(src[i]);
      script.src = src[i];
      document.body.appendChild(script);
    }*/

  },
  mounted() {
    console.log("等待...");
    //console.log("mounted");
    let timer = setInterval(() => {
      //需要定时执行的代码
      console.log("等待...");
      if (window.mapv){
        console.log("已加载...");
        clearInterval(timer)
        //this.aggData();
      }
    },2000);


/*      while (!window.mapv){
        console.log("mounted");
        setTimeout(() => {
          console.log("等待...");
        }, 1000);
      }*/
  }
}
</script>

<style lang="less">
  //@import "../../../my-theme/template";
  #allmap {
    width: 100%;
    height: 100%;
    margin: 0;
  }
</style>
